import axios from 'axios'
import store from '@/store'
import router from '@/router'

const service = axios.create({
  baseURL: process.env.VUE_APP_BASE_API,
  timeout: 10000
})
// 取消请求收集器
const cancelArr = []
export const cancelAll = () => {
  cancelArr.filter((item) => {
    item.fn()
    return false
  })
}
// request interceptor
service.interceptors.request.use(
  (config) => {
    // 取消相同的上一个请求
    cancelArr.filter((item) => {
      if (item.url === config.url && item.method === config.url) {
        item.fn()
        return false
      }
      return true
    })
    // 添加取消请求的函数
    config.cancelToken = new axios.CancelToken((cancenFn) => {
      cancelArr.push({
        url: config.url,
        method: config.method,
        fn: cancenFn
      })
    })
    // 全局设置请求头
    if (store.state.user.token) {
      config.headers.Authorization = `Bearer ${store.state.user.token}`
    }
    return config
  },
  (err) => {
    return Promise.reject(err)
  }
)

// response interceptor
service.interceptors.response.use(
  (response) => {
    return response.data.data
  },
  (err) => {
    if (err.response) {
      if (err.response.status === 401) {
        // 登录超时
        store.commit('user/logout')
        store.commit('permission/setRoutes', [])
        router.push(`/login?redirect=${window.location.href.split('#'[1])}`)
        // router.push('/login')
      }
      console.log(err.response)
    }

    return Promise.reject(err)
  }
)

export default service
